


import {watchValueChange, canvasClip, getTextWidth, globalCtx, px} from '../libs/utils.js';
import View from "./view";

// const fontFamily = 'Georgia,"Times New Roman",Times,SimSun,FontAwesome,serif';
/// 图片文字
export default class ImgText extends View {
    //// width 组件宽   height 组件高 /  imgWidth图片宽 imgHeight 图片高
    ////
    constructor(imgSrc = '', x, y, width, height, imgWidth = 0, imgHeight = 0,text = '',textAlign = 'center',strokeStyle = '#e5883c') {
        super(x, y, width, height);

        this.text = text || '';
        this.imgSrc = imgSrc;
        this.imgWidth = imgWidth;
        this.imgHeight = imgHeight;
        this.childSize = { x, y, width: imgWidth, height: imgHeight };
        this.size = 'full';  // 切记 size 的赋值需在 position 之前
        this.position = 'top left';
        this.repeat = 'no-repeat';
        this.fontSize = 23;
        this.lineHeight = this.fontSize *1.2;
        this.textWrap = false;//不换行
        // 绑定数值联动
        watchValueChange(this, 'imgSrc', val => {
            const img = new Image();
            img.src = imgSrc;
            img.onload = () => {
                this.imgWidth = px(img.width);
                this.imgHeight = px(img.height);
                this.img = img;
                this.resize();
            }
            img.onerror = (err) => {
                console.log(err);
                this.resize();
            }
        });
        ['width', 'height', 'size', 'position'].forEach(key => {
            watchValueChange(this, key, (val) => {
                this.resize();
            });
        });
        ['x', 'y'].forEach(key => {
            watchValueChange(this, key, (val) => {
                this.resize();
            }, 0);
        });
        this.imgSrc = imgSrc;

        // 绑定数值联动
        watchValueChange(this, 'fontSize', (val) => {
            this.lineHeight = val * 1.2;

            this.resize();
        });
        ['maxWidth', 'textWrap', 'text'].forEach(key => {
            watchValueChange(this, key, (val) => {
                this.resize();
            });
        });
        this.maxWidth = imgWidth;
        // 其他重要赋值
        this.color = '#fff';
        // this.color = 'pink';
        // this.borderColor = 'pink'
        // // canvas.setStrokeStyle('pink'); // 设置描边颜色为粉红色
        this.textAlign = textAlign;
        this.strokeStyle = strokeStyle;
        this.resize();
    }

    customDrawToCanvas(ctx) {

        ctx.save();
        const { img, x, y, width, height } = this;
        const { x: newImgX, y: newImgY, width: newImgWidth, height: newImgHeight } = this.childSize;
        if (!img) return;

        // 要绘制的图片若超出了容器，则采用裁剪
        if (x > newImgX || y > newImgY || x + width < newImgX + newImgWidth || y + height < newImgY + newImgHeight) {
            return canvasClip(ctx, x, y, width, height, (_tempCtx) => {
                _tempCtx.drawImage(img, newImgX, newImgY, newImgWidth, newImgHeight);
            });
        }
        ctx.drawImage(img, newImgX, newImgY, newImgWidth, newImgHeight);


        const { childTextSize: { json } } = this;
        const { maxWidth, fontSize, lineHeight, color, textAlign } = this;


        ctx.textBaseline = 'top';
        ctx.fillStyle = color;
        ctx.font = `${fontSize}px ZCOOL KuaiLe`;

        let imageWidth = width;
        // 设置描边样式
        ctx.strokeStyle = this.strokeStyle;
        ctx.lineWidth = 3

        json.forEach(({ text, width }, index) => {
// 绘制描边的字体
            switch (textAlign) {
                case 'center': ctx.strokeText(text, x + (newImgWidth-width)/2, y +newImgHeight/2- (index+1) * fontSize); break;
                case 'bottom': ctx.strokeText(text, x + (newImgWidth-width)/2, y +newImgHeight/2+ (index+1) * fontSize); break;
                case 'right': ctx.strokeText(text, x + maxWidth - width, y + index * lineHeight); break;
                case 'left': default: ctx.strokeText(text, x, y+ height/2-this.fontSize + index * lineHeight);
            }
            switch (textAlign) {
                case 'center': ctx.fillText(text, x + (newImgWidth-width)/2, y +newImgHeight/2- (index+1) * fontSize); break;
                case 'bottom': ctx.fillText(text, x + (newImgWidth-width)/2, y +newImgHeight/2+ (index+1) * fontSize); break;
                case 'right': ctx.fillText(text, x + maxWidth - width, y + index * lineHeight); break;
                case 'left': default: ctx.fillText(text, x, y+ height/2-this.fontSize + index * lineHeight);
            }

        });


        ctx.restore();
    }

    resize() {
        const { width, height } = this.getImgRealSize();
        this.childSize = { ...this.childSize, width, height };
        const { newImgX: x, newImgY: y } = this.getImgPosition();
        this.childSize = { ...this.childSize, x, y };

        const { text = '' } = this;
        this.childTextSize = this.getTextWrapJson(text);


    }

    /**
     * 计算图片实际宽高，比如 full cover contian 或者 50 50px 10%
     */
    getImgRealSize() {
        const { width, height, imgWidth, imgHeight, size } = this;
        let newImgWidth = 0, newImgHeight = 0;

        const ratio = height !== 0 ? width / height : 1;
        const imgRatio = imgHeight !== 0 ? imgWidth / imgHeight : 1;
        if (size === 'full') {
            newImgWidth = width;
            newImgHeight = height;
        } else if (size === 'contain') { // 让图片短边与容器贴合，长边超出
            if (ratio > imgRatio) {
                newImgHeight = height;
                newImgWidth = newImgHeight * imgRatio;
            } else {
                newImgWidth = width;
                newImgHeight = newImgWidth / imgRatio;
            }
        } else if (size === 'cover') { // 让图片长边与容器贴合，短边留白
            if (ratio < imgRatio) {
                newImgHeight = height;
                newImgWidth = newImgHeight * imgRatio;
            } else {
                newImgWidth = width;
                newImgHeight = newImgWidth / imgRatio;
            }
        } else {  // 让图片保存定值或百分比
            const temp = size.split(' ');
            if (temp.length === 1) temp.concat(temp);
            if (temp.length === 0) temp.splice(0, 1, 0, 0);

            temp.forEach((item, index) => {
                let value = 0;
                if (/\d+%/.test(item)) { value = width * parseFloat(item) / 100; }
                else { value = parseFloat(item); }  // 包括 px 哟
                index === 0 ? (newImgWidth = value) : (newImgHeight = value);
            });
        }

        return { width: newImgWidth, height: newImgHeight };
    }

    /**
     * 计算图片实际位置，比如 left center top right 或者 50 10% 等
     */
    getImgPosition() {
        const { x, y, width, height, position } = this;
        const { width: newImgWidth, height: newImgHeight } = this.childSize;
        let newImgX = 0, newImgY = 0;

        const temp = position.split(' ');
        if (temp.length === 0) return { newImgX: 0, newImgY: 0 };
        if (temp.length === 1) temp.push('center');  // 只传入一个时，另一个默认为 center
        if ((temp[0] === 'top' || temp[0] === 'bottom')) temp.reverse();  // 把 top bottom 放到后面去
        if ((temp[1] === 'left' || temp[1] === 'right')) temp.reverse();  // 如果 left right 在后面则调到前面

        temp.forEach((item, index) => {
            var value = 0;
            if (item === 'top') value = y;
            else if (item === 'bottom') value = y + height - newImgHeight;
            else if (item === 'left') value = x;
            else if (item === 'right') value = x + width - newImgWidth;
            else if (item === 'center' && index === 0) value = x + width / 2 - newImgWidth / 2;
            else if (item === 'center' && index === 1) value = y + height / 2 - newImgHeight / 2;
            else if (/\d+%/.test(item)) { value = (index === 0 ? x : y) + width * parseFloat(item) / 100; }
            else { value = (index === 0 ? x : y) + parseFloat(item); }  // 包括 px 哟
            index === 0 ? (newImgX = value) : (newImgY = value);
        });

        return { newImgX, newImgY };
    }


    /**
     * 根据 maxWidth 和 textWrap 获取文本显示的 json 结构
     */
    getTextWrapJson(text) {
        const { fontSize, lineHeight, maxWidth, textWrap, x, y } = this;

        // 如果不定宽，则直接返回
        if (maxWidth === Infinity) {
            const realCharWidth = getTextWidth(text, fontSize);

            return { x, y, width: realCharWidth, height: lineHeight, json: [{ text: text, width: realCharWidth }] };
        }

        const json = []; // 每行文本的数据
        const dotWidth = getTextWidth('...', fontSize);

        for (let i in text) {
            let char = text[i];
            let item = json.slice(-1)[0];
            if (!item) item = { text: '', width: 0 }
            let realCharW = getTextWidth(item.text + char, fontSize);

            if (textWrap === true) { // 换行
                if (realCharW <= maxWidth) {
                    item.text += char;
                    item.width = realCharW;
                    json.splice(-1, 1, item);
                } else {
                    item = { text: char, width: realCharW };
                    json.push(item);
                }
            } else {  // 不换行
                if (realCharW <= maxWidth ) {
                    item.text += char;
                    item.width = realCharW;
                    json.splice(-1, 1, item);
                } else {

                    // item.text += '...';
                    item.text += char;
                    item.width = maxWidth;
                    json.splice(-1, 1, item);
                    return { x, y, textWidth: maxWidth, textHeight: lineHeight, json };
                }
            }
        }

        return {
            x, y,
            textWidth: maxWidth,
            textHeight: lineHeight * json.length,
            json,
        };
    }

}
